package com.basic.business.common.utils;

import com.basic.business.log.domain.TOrdersLog;
import com.basic.business.order.domain.TOrdersMain;
import jcifs.CIFSContext;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 文件处理工具类
 *
 * @author zhaoxy_jn@163.com
 */
@Slf4j
public class FileUtils {

    static {
        // 设置 SMB 连接池配置
        System.setProperty("jcifs.smb.client.maxConnections", "10000");
        System.setProperty("jcifs.smb.client.soTimeout", "3000000");
    }

    /**
     * 创建文件夹
     */
    public static void createDirectories(String dirPath) throws IOException {
        CIFSContext cifsContext = null;
        try {
            cifsContext = CifsContextPool.borrowContext();
            SmbFile smbDir = new SmbFile(dirPath, cifsContext);

            if (!smbDir.exists()) {
                smbDir.mkdirs();
            }
        } catch (Exception e) {
            throw new IOException("Failed to create directories", e);
        } finally {
            if (cifsContext != null) {
                if (cifsContext instanceof Closeable) {
                    ((Closeable) cifsContext).close();
                }
                CifsContextPool.returnContext(cifsContext);
            }
        }
    }




    /**
     * 从HTTP下载文件到SMB
     * @param httpUrl 网络路径
     * @param smbPath 共享路径
     */
    public static String downloadFileFromHttpToSmb(String httpUrl, String smbPath) throws Exception {
        HttpURLConnection httpConn = null;
        InputStream inputStream = null;
        SmbFileOutputStream smbOutputStream = null;
        CIFSContext cifsContext = null;
        String uniqueSmbPath = null;
        try {
            // 打开HTTP连接
            URL url = new URL(httpUrl);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");
            httpConn.setConnectTimeout(30000); // 设置连接超时时间
            httpConn.setReadTimeout(30000);    // 设置读取超时时间

            // 检查HTTP响应码
            int responseCode = httpConn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取HTTP响应流
                inputStream = httpConn.getInputStream();

                // 生成唯一的SMB文件路径
                uniqueSmbPath = getUniqueFilePath(smbPath);

                // 创建SMB文件对象
                cifsContext = CifsContextPool.borrowContext();
                SmbFile smbFile = new SmbFile(uniqueSmbPath, cifsContext);

                // 使用 try-with-resources 确保流关闭
                try (SmbFileOutputStream smbOutputStreamLocal = new SmbFileOutputStream(smbFile)) {
                    smbOutputStream = smbOutputStreamLocal;
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        smbOutputStream.write(buffer, 0, bytesRead);
                    }
                }

            } else {
                throw new Exception("Failed to download file from HTTP to SMB. HTTP response code: " + responseCode);
            }
        } catch (Exception e) {
            throw new Exception("Failed to download file from HTTP to SMB", e);
        }finally {
            // 归还 CIFSContext 到连接池
            if (cifsContext != null) {
                CifsContextPool.returnContext(cifsContext);
            }
            // 关闭资源
            if (inputStream != null) {
                inputStream.close();
            }
            if (smbOutputStream != null) {
                smbOutputStream.close();
            }
            if (httpConn != null) {
                httpConn.disconnect();
            }
        }
        return uniqueSmbPath;
    }

    /**
     * 获取唯一文件路径
     */
    public static String getUniqueFilePath(String smbPath) throws Exception {
        CIFSContext cifsContext = null;
        try {
            // 从连接池获取 CIFSContext
            cifsContext = CifsContextPool.borrowContext();
            SmbFile smbFile = new SmbFile(smbPath, cifsContext);

            // 如果文件不存在，直接返回原路径
            if (!smbFile.exists()) {
                return smbPath;
            }

            // 获取父目录和文件名
            String parentDir = smbFile.getParent();
            String fileName = smbFile.getName();

            // 分离文件名和扩展名
            String baseName = fileName.substring(0, fileName.lastIndexOf('.'));
            String extension = fileName.substring(fileName.lastIndexOf('.'));

            int index = 1;
            String uniqueFileName;
            SmbFile uniqueFile;
            do {
                // 生成唯一文件名
                uniqueFileName = baseName + "(" + index + ")" + extension;
                uniqueFile = new SmbFile(parentDir + uniqueFileName, cifsContext);
                index++;
            } while (uniqueFile.exists());

            // 返回唯一文件的绝对路径
            return uniqueFile.getCanonicalPath();
        } finally {
            // 归还 CIFSContext 到连接池
            if (cifsContext != null) {
                CifsContextPool.returnContext(cifsContext);
            }
        }
    }

    /**
     * 根据Windows共享路径删除文件或文件夹
     *
     * @param smbPath SMB路径，可以是文件或文件夹
     */
    public static int deleteFromSmb(String smbPath) {
        int deletedCount = 0;
        CIFSContext cifsContext = null;
        try {
            if (smbPath == null || smbPath.isEmpty()) {
                return 0;
            }
            cifsContext = CifsContextPool.borrowContext();
            SmbFile smbFile = new SmbFile(smbPath, cifsContext);

            if (!smbFile.exists()) {
                return 0; // 如果路径不存在，直接返回
            }

            if (smbFile.isFile()) {
                // 如果是文件，删除文件
                smbFile.delete();
                // 检查并删除空文件夹
                deleteEmptyParentFolder(smbFile);
                return 1;
            } else if (smbFile.isDirectory()) {
                // 如果是文件夹，递归删除文件夹及其内容
                return deleteFolder(smbFile);
            }
        } catch (Exception e) {
            log.error("Error deleting from SMB path: {}", smbPath, e);
            return 0;
        } finally {
            if (cifsContext != null) {
                CifsContextPool.returnContext(cifsContext); // 归还连接至连接池
            }
        }
        return 0;
    }

    /**
     * 递归删除文件夹及其内容
     *
     * @param folder 要删除的文件夹
     */
    private static int deleteFolder(SmbFile folder) throws Exception {
        if (!folder.exists() || !folder.isDirectory()) {
            return 0;
        }
        int deletedCount = 0;
        if (folder.isDirectory()) {
            for (SmbFile file : folder.listFiles()) {
                if (file.isDirectory()) {
                    deletedCount += deleteFolder(file);
                } else {
                    file.delete();
                    deletedCount++;
                }
            }
        }
        // 删除空文件夹
        folder.delete();

        return deletedCount;
    }

    /**
     * 删除空父文件夹
     *
     * @param smbFile 文件或文件夹对象
     */
    private static void deleteEmptyParentFolder(SmbFile smbFile) throws Exception {
        if (smbFile == null) {
            return;
        }

        // 获取父文件夹路径
        String parentPath = smbFile.getParent();
        if (parentPath == null) {
            return; // 如果没有父文件夹，直接返回
        }

        SmbFile parentFolder = new SmbFile(parentPath, smbFile.getContext());

        // 检查并删除空文件夹
        if (parentFolder.exists() && parentFolder.isDirectory() && parentFolder.list().length == 0) {
            parentFolder.delete();
        }
    }

    /**
     * 重命名SMB路径
     */
    public static void renameSmbPath(String originalPath, String newPath){
        if (originalPath == null || newPath == null) {
            throw new IllegalArgumentException("路径不能为空");
        }

        // 检查并规范化路径
        CIFSContext cifsContext = null;
        try {
            cifsContext = CifsContextPool.borrowContext();
            SmbFile originalSmbFile = new SmbFile(originalPath, cifsContext);

            // 确保新路径有效
            SmbFile newSmbFile = new SmbFile(newPath, cifsContext);

            // 执行重命名操作
            originalSmbFile.renameTo(newSmbFile);


        } catch (Exception e) {
            log.error("Error renaming SMB path: {}", originalPath, e);
        }finally {
            if (cifsContext != null) {
                CifsContextPool.returnContext(cifsContext); // 归还连接至连接池
            }
        }
    }

    public static void main(String[] args) throws Exception {
//        createDirectories("smb://127.0.0.1/process/2025/02/18/UV事业部/中班/3C事业部/9mmpvc/常规9mmpvc/中奥晋呈旗舰店/3592608+中奥晋呈旗舰店");
//        String smbPath = "smb://192.168.30.61/自动处理/2025年03月/18日/UV事业部/4班次/3C事业部/9mmpvc/常规9mmpvc/中奥晋呈旗舰店/4027199+中奥晋呈旗舰店";
//        renameSmbPath(smbPath, "smb://192.168.30.61/自动处理/2025年03月/18日/UV事业部/4班次/3C事业部/9mmpvc/常规9mmpvc/中奥晋呈旗舰店/4027199+中奥晋呈旗舰店+发顺丰快递");
//        renameSmbPath(smbPath,"smb://192.168.200.83/自动处理/2025年03月/02日/写真事业部/中班/3C事业部/打包/卷材/中奥晋呈旗舰店/3775596+中奥晋呈旗舰店+收据/1张 20x15 夜光膜(1).jpg");




        TOrdersMain ordersMain = new TOrdersMain();
        ordersMain.setSellerMemo("【顺丰到付】");
        boolean isReceipt = ordersMain.getDetailList().stream().anyMatch(detail -> StringUtils.containsAny(detail.getSellerMemo(), "【顺丰到付】", "【顺丰现付】"));
        boolean isMainReceipt = StringUtils.containsAny(ordersMain.getSellerMemo(), "【顺丰到付】", "【顺丰现付】");
        System.out.println(isMainReceipt);
        System.out.println(isReceipt);
        if (isReceipt || isMainReceipt) {
            System.out.println("11111111111");
        }

    }


}
